﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;

namespace V5_EaspLibs.Core {
    /// <summary>
    /// 软件注册类
    /// </summary>
    public class SoftRegionHelper {
        private static readonly SoftRegionHelper m_Instance = new SoftRegionHelper();
        /// <summary>
        /// 
        /// </summary>
        public static SoftRegionHelper Instance {
            get { return m_Instance; }
        }
        /// <summary>
        /// 生成公钥和私钥
        /// </summary>
        /// <returns></returns>
        public string CreatePublicPrivateCode() {
            using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider()) {
                // 公钥 
                string pubkey = rsa.ToXmlString(false);
                // 私钥 
                string prikey = rsa.ToXmlString(true);
                return pubkey + "||||" + prikey;
            }
        }
        /// <summary>
        /// 生成注册码
        /// </summary>
        /// <param name="prikey">私钥字符串</param>
        /// <param name="sUserName">用户名</param>
        /// <returns>注册码</returns>
        public string CreateRegionCode(string prikey, string sUserName) {
            using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider()) {
                rsa.FromXmlString(prikey);
                // 加密对象 
                RSAPKCS1SignatureFormatter f = new RSAPKCS1SignatureFormatter(rsa);
                f.SetHashAlgorithm("SHA1");
                byte[] source = System.Text.ASCIIEncoding.ASCII.GetBytes(sUserName);
                SHA1Managed sha = new SHA1Managed();
                byte[] result = sha.ComputeHash(source);

                byte[] b = f.CreateSignature(result);
                return Convert.ToBase64String(b);
            }
        }
        /// <summary>
        /// 验证注册码
        /// </summary>
        /// <param name="pubkey">公钥字符串</param>
        /// <param name="cCode">验证字符串</param>
        /// <param name="sUserName">用户名</param>
        /// <returns></returns>
        public bool CheckRegionCode(string pubkey, string cCode, string sUserName) {
            using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider()) {
                rsa.FromXmlString(pubkey);
                RSAPKCS1SignatureDeformatter f = new RSAPKCS1SignatureDeformatter(rsa);
                f.SetHashAlgorithm("SHA1");
                byte[] key = Convert.FromBase64String(cCode);
                SHA1Managed sha = new SHA1Managed();
                byte[] name = sha.ComputeHash(ASCIIEncoding.ASCII.GetBytes(sUserName));
                if (f.VerifySignature(name, key))
                    return true;
                else
                    return false;
            }
        }
    }
}
